//
//  ComposeViewController.swift
//  weibo10
//
//  Created by 晁岳山 on 15/10/25.
//  Copyright © 2015年 晁岳山. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
class ComposeViewController: UIViewController {
    
    //MARK: - 视图生命周期
    override func viewDidAppear(animated: Bool) {
        if picturePickerController.view.bounds.height <= 0 {
            
            textView.becomeFirstResponder()
        }
    }
    //MARK: - 监听键盘
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    //监听事件
    //字典中的结构体是NSValue
    //字典中的数值是NSNumber
    @objc private func keyboardChanged(n: NSNotification) {
        //1.计算出偏移的frame
        let rect = (n.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        //2.计算动画时间
        let duration = (n.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        let offSet = -UIScreen.mainScreen().bounds.height + rect.origin.y
        //跟新toolBar的约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offSet)
        }
        // 3.计算动画曲线
        let curve = (n.userInfo!["UIKeyboardAnimationCurveUserInfoKey"] as! NSNumber).integerValue

        //设置动画曲线
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }

    override func loadView() {
        view = UIView()
        setupUI()
    }
    
    //注销监听
   deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }


    //MARK: - 事件监听
    @objc private func cancelVC() {
        //先退掉键盘
        textView.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    //MARK: - 发送微博
    @objc private func sentStatus() {
        
        let text = textView.finishEmotionText
        NetworkTools.sharedTools.sendStatus(text) { (result, error) -> () in
            if error != nil {
                print(error)
                SVProgressHUD.showErrorWithStatus("您的网络不给力，请重新加载")
                return
            }
            print(result)
        }
        
        self.cancelVC()
    }
    
    
    //MARK: - 表情键盘事件
    @objc private func emoticonbutton() {
        // 1. 退掉键盘
        textView.resignFirstResponder()
        // 2. 设置键盘
        textView.inputView = textView.inputView == nil ? emoticonView : nil
        // 3. 显示键盘
        textView.becomeFirstResponder()
    }
     //MARK: - 照片选择器
     @objc private func toolbar() {
        //退掉键盘
        textView.resignFirstResponder()
        //多次点击按钮的话 会不断的更新约束  加上判断  如果约束已经更新的话  就不在更新
        if picturePickerController.view.bounds.height > 0 {
            return
        }
        //更新约束
        picturePickerController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height * 0.6)
        }
        textView.snp_remakeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(picturePickerController.view.snp_top)
        }
        //添加动画
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    //MARK: - 懒加载
    private lazy var toolBar: UIToolbar = UIToolbar()
    private lazy var textView: UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        //竖直方向上始终允许滚动
        tv.alwaysBounceVertical = true
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        tv.delegate = self
        return tv
    }()
    //占位标签
    private lazy var placeLabel: UILabel = UILabel(content: "分享新鲜事...", fontSize: 18, color: UIColor.lightGrayColor())
    //表情
    private lazy var emoticonView: EmoticonView = EmoticonView { [weak self] (emoticon) -> () in
        self?.textView.insertEmoticon(emoticon)
    }
    //照片选择控制器
    private lazy var picturePickerController: PicturePickerController = PicturePickerController()
}

// MARK: - 设置界布局
extension ComposeViewController {
    private func setupUI() {
       toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        //添加控件
        view.addSubview(toolBar)
        view.addSubview(textView)
        textView.addSubview(placeLabel)
        //设置布局
        prepareNavigationBar()
        prepareToolBar()
        prepareTextView()
        preparePicturePicker()
        //取消自动设置的在导航栏下方
        automaticallyAdjustsScrollViewInsets = false
    }
    // MARK: - 准备picturePickerController
    private func preparePicturePicker() {
        //添加子控制器 如果不添加这句话  就会报错误信息  并且图片不会显示
        addChildViewController(picturePickerController)
        view.insertSubview(picturePickerController.view, belowSubview: toolBar)
        picturePickerController.view.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(0)
        }
    }
    //MARK: - 准备textView
    private func prepareTextView() {
        //设置textView 的自动布局
        textView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolBar.snp_top)
        }
        //设置placeLabel的自动布局
        placeLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(textView.snp_left).offset(5)
            make.top.equalTo(textView.snp_top).offset(8)
        }
        //监听textView的valueChanged
        
    }
    
    //MARK: - 准备toolBar
    private func prepareToolBar() {
        //设置自动布局
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(44)
        }
        //设置内容
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "toolbar"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticonbutton"],
            ["imageName": "compose_addbutton_background"]]
        var items = [UIBarButtonItem]()
        for dict in  itemSettings {
          let button = UIButton(imageName: dict["imageName"]!, backImageName: nil)
            let item = UIBarButtonItem(customView: button)
            items.append(item)
            // 添加表情的点击事件
            if let actionName = dict["action"] {
                button.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
            }
            //添加弹簧
            let item1 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            items.append(item1)
        }
        items.removeLast()
        toolBar.items = items
    }
    //MARK: - 准备navigationBar
    private func prepareNavigationBar() {
        //设置颜色
        //1.左侧按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self , action: "cancelVC")
        //2.右侧按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "确定", style: UIBarButtonItemStyle.Plain, target: self, action: "sentStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        //2.中间的label按钮
        //TODO: 这儿为什么设置36 不是44
        let titleView = UIView(frame: CGRectMake(0, 0, 200, 36))
        navigationItem.titleView = titleView
        let titleLabel = UILabel(content: "发微博", fontSize: 15)
        titleView.addSubview(titleLabel)
        let nameLabel = UILabel(content: UserAccountViewModel.sharedUserViewMModel.account?.screen_name ?? "",
            fontSize: 13,
            color: UIColor.lightGrayColor())
        titleView.addSubview(nameLabel)
        //设置自动布局
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
}
// MARK: - UITextViewDelegate
extension ComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeLabel.hidden = textView.hasText()
    }
}


